/*
 * Copyright (C) 2014 Alpha, Inc.
 * This is NOT a freeware, use is subject to license terms.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gehua.octopus.rpc.starter;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author guna
 */
public class StartUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(StartUtil.class);
    private StartUtil(){
        
    }
    public static void processKeypair(String keypair, Map<String, String> map) {
        if (keypair == null) {
            return;
        }
        String[] split = keypair.split("=");
        if (split.length > 1) {
            String key = split[0];
            String value = split[1];
            if (map.containsKey(key)) {
                LOGGER.warn("Duplication config [{},{}].", key, value);
            }
            map.put(key, value);
        }
        /*
         if (split.length == 2 && "rpc-server.state".equals(split[0])) {
         configureServerStateFile(split[1], server);
         }
         */
    }
    public static Map<String, String> processArgs(String[] args) {
        Map<String, String> map = new HashMap<>();
        if (args == null) {
            return map;
        }
        for (String string : args) {
            if (string.contains("=")) {
                processKeypair(string, map);
            }
        }
        return map;
    }
    
    public static String getAPPBase(Map<String, String> mapArgs) {
        String appBase;
        if (mapArgs.containsKey("rpc-server.base")) {
            appBase = mapArgs.get("rpc-server.base");
            LOGGER.info("Setting app base to [{}], (By init params).", appBase);
        } else if (System.getProperty("rpc-server.base") != null) {
            appBase = System.getProperty("rpc-server.base");
            LOGGER.info("Setting app base to [{}],(By system property).", appBase);
        } else {
            String appRoute = App.class.getProtectionDomain().
                    getCodeSource().getLocation().getPath();
            int lastIndexOf = appRoute.lastIndexOf('/');
            if (lastIndexOf > -1) {
                appRoute = appRoute.substring(0, lastIndexOf);
            }
            LOGGER.info("Setting app base to [{}], (By auto detected).", appRoute);
            appBase = appRoute;
        }
        return appBase;
    }
}
